<?php

function map_location_init() {
	
    global $CONFIG;
    register_page_handler('locations', 'map_location_page_handler');
  //  add_menu(elgg_echo('map_location:menu'), $CONFIG->wwwroot . 'pg/locations/all');    
    elgg_extend_view('metatags','map_location/maps/metatags');
}

function map_location_page_handler($page) {

    global $CONFIG;

    if (isset($page[0])) {
        switch ($page[0]) {
            case 'all' :
                include($CONFIG->pluginspath . 'map_location/views/default/map_location/view.php');
                break;
            case 'search' :            	
                include($CONFIG->pluginspath . 'map_location/views/default/map_location/view.php');
                break;    
            case 'producer':
                if (isset($page[1])) {
				   set_input('producer',$page[1]);
			    }
			    set_context('producer');
			    include($CONFIG->pluginspath . 'map_location/views/default/map_location/view.php');
            	break;           	  
             default :
                include($CONFIG->pluginspath . 'map_location/views/default/map_location/view.php');
                break;
	        }                
    } else {
        forward($_SERVER['HTTP_REFERER']);
    }
}

function get_producers_close_entity($guids){
	   
	if (empty($guids)){
		return null;
	}	
	$options = array ('metadata_names' => array ('address_longitude', 'adress_latitude'),	                  
	                  'wheres' => array( 'e.guid in ('. $guids . ')'));  
	$producers = elgg_get_entities_from_metadata($options);	
	return $producers;
}

//this method will return all categories that producer has product in array format
function get_categories_producer($producer_guid, $prepared){
   
   global $CONFIG;	
   
   define("SUBTYPES", "stores");
   define("LOOKING_FOR", "category");
   
   $sql ="select valor.string as valor
          from 
            {$CONFIG->dbprefix}entities ent
            join {$CONFIG->dbprefix}entity_subtypes sub on ent.subtype = sub.id
            join {$CONFIG->dbprefix}metadata met on ent.guid = met.entity_guid
            join {$CONFIG->dbprefix}metastrings valor on met.value_id = valor.id
            join {$CONFIG->dbprefix}metastrings nome on nome.id = met.name_id  
          where
             sub.subtype = '". SUBTYPES ."' and
             met.owner_guid = {$producer_guid} and 
             nome.string = '".LOOKING_FOR."'";   
   $result = get_data($sql, "entity_row_to_elggstar");
   if ($prepared){
   	   $prepared = array();
   	   $i = 0;
   	   foreach ($result as $value){
   	   	  $prepared[$i] = $value->valor; 
   	   	  $i++;
   	   }
   	   return $prepared;   	
   } else return $result;  
}

function prepared_array($params){
	$result = '';
	$params_count = count($params);
	$count = 1;
	foreach ($params as $value){
		if ($count < $params_count){
			$result .= $value->entity_guid . ', ';  
		} else $result .= $value->entity_guid ;
		$count++;
	}

	return 	$result;
}

//function get_produceres_close($guid, $lat, $lon, $count){
function get_produceres_close($lat, $lon, $count){
	
	if ( empty($lat) || empty($lon)){
		register_error("Tem alguma coisa null");		
		return null;
	}
	// por enquanto em 100 km
	$rad = 100	; // radius of bounding circle in kilometers
    $R = 6371;  // earth's radius, km
  
  // first-cut bounding box (in degrees)
    $maxLat = $lat + rad2deg($rad/$R);
    $minLat = $lat - rad2deg($rad/$R);
  // compensate for degrees longitude getting smaller with increasing latitude
    $maxLon = $lon + rad2deg($rad/$R/cos(deg2rad($lat)));
    $minLon = $lon - rad2deg($rad/$R/cos(deg2rad($lat)));	
    
    $lat = deg2rad($lat);
    $lon = deg2rad($lon);   
 
    $sql ="        
         from (select entity_guid, Lat, Lon
               from elgg_all_latlng
               where 
                  Lat > $minLat and Lat < $maxLat and
                  Lon > $minLon and Lon < $maxLon ) as FirstCut 
         where 
           acos(sin($lat) * sin(radians(Lat)) + 
           cos($lat) * cos(radians(Lat)) * cos(radians(Lon) - $lon)) * $R < $rad
         order by distance ";
    if ($count){
    	$sql = "select count(*) as total " .$sql;
        $result = get_data_row($final);
        return (int)$total->total;    	
    }else {
       $sql = "
         select 
           entity_guid, Lat, Lon, 
           acos(sin($lat) * sin(radians(Lat)) + cos($lat) * cos(radians(Lat)) * cos(radians(Lon) - $lon)) * $R As distance "
         .$sql;           
       
       $dt = get_data($sql, "entity_row_to_elggstar");            
       
       $guids = prepared_array($dt);
             
       $result = get_producers_close_entity($guids);                   
    
       return $result;           	
    }
}

function get_toltip($producer){
	return elgg_view('map_location/toltip', array('entity' => $producer, 'guid' => $producer->guid ));;	
} 

function get_markers($producers) {
    $markers = array();
    $z = 1;    
    foreach ($producers as $producer) {
        if ($producer instanceof ElggEntity && $producer->getType() == 'user') {
        	$long = get_metadata_byname($producer->guid, 'address_longitude');
        	$lat = get_metadata_byname($producer->guid, 'address_latitude');
            $markers[] = array($producer['name'], 
                               $lat->value, 
                               $long->value, 
                               $producer->getIcon('small'),
                               get_toltip($producer),
                               $z, 
                               $producer->getURL(), 
                               $producer->guid,                              
                               get_categories_producer($producer->guid, true));
        }
        $z++;
    }      
    return $markers;
}

register_elgg_event_handler('init', 'system', 'map_location_init');

?>
